package com.woohua.thread.lockscene;

import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;

/***
 * @title ReentrantLockDemo
 * @description： 读读互斥、读写互斥、写写互斥，如果不想对读加锁，那么取消读操作里的加锁操作则可
 * @author woo hua
 * @version 1.0.0
 * @create 2023/3/21 11:17
 **/
public class ReentrantLockDemo {

    private static int TOTAL_THREAD_NUM = 3; // 总共线程数
    private static int WRITE_THREAD_NUM = 1; // 写线程数
    private static int READ_THREAD_NUM = TOTAL_THREAD_NUM - WRITE_THREAD_NUM; // 读线程数

    public static void main(String[] args) {
        ReentrantLockCache reentrantLockCache = new ReentrantLockCache();
        ExecutorService executorService = Executors.newFixedThreadPool(TOTAL_THREAD_NUM);
        AtomicInteger value = new AtomicInteger();
        value.getAndIncrement();

        for (int i = 0; i < WRITE_THREAD_NUM; i++) {
            executorService.submit(() -> {
                while (true) {
                    int v = value.getAndIncrement();
                    reentrantLockCache.put(1001, v);
                    System.out.println(Thread.currentThread().getName() + "-写 value: " + v + " " + new Date());
                }
            });
        }

        for (int i = 0; i < READ_THREAD_NUM; i++) {
            executorService.submit(() -> {
                int callTimes = 0;
                while (true) {
                    System.out.println(Thread.currentThread().getName() + "-读 value: " + reentrantLockCache.get(1001) + " " + new Date());
                }
            });
        }
    }

    public static void sleep(long millis) {
        try {
            Thread.sleep(millis);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
